﻿Imports ADOEntity
Imports System.Data
Partial Class Administrator_frmZone
    Inherits Web.UI.BasePage
    Private Const strMenuCode As String = "M69"
    Dim sDeptEntity As userEntities
    Dim dsZone As New DataSet
    Dim clsQuery As clsDatabase
    Dim clsDataTable As New clsLINQToDataTable
    Dim intBeforeItemIndex As Integer
    Dim clsSessionMenuRight As clsSessionMenuRight = New clsSessionMenuRight
    Dim strMsg As String = ""
    Dim clsMasterDropDown As clsMasterDropDown

#Region " Even Page "
    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        lblZoneCode.Text = Resources.resZone.ZoneCode & " : "
        lblZoneName.Text = Resources.resZone.ZoneName & " : "
        lblDept.Text = Resources.resBranch.department & " : "
        btnSearch.Text = Resources.resButton.btnSearch
        btnAdd.Text = Resources.resButton.btnAdd
        btnModify.Text = Resources.resButton.btnModify
        btnDelete.Text = Resources.resButton.btnDelete
        btnClear.Text = Resources.resButton.btnClear
        btnPrint.Text = Resources.resButton.btnPrint

        lblMsg.Text = Resources.resMessageAlert.alertEmptyGrid
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            chkIsLogin()
            clsMasterDropDown = New clsMasterDropDown
            sDeptEntity = New UserEntities
            clsSessionMenuRight = Session("clsMenuRight")

            If (Not IsPostBack) Then
                CreateControlMP()
                loadDataToDropDown()
                setButton(1)
                setUserRightButton()
            Else
                dsZone = Session("dsTblMaster")
                gvZone.DataSource = dsZone.Tables("sZone")
                gvZone.DataBind()
            End If
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('เกิดข้อผิดพลาดในการโหลด')", True)
        End Try


    End Sub

    Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
        Session("dsTblMaster") = dsZone
    End Sub

#End Region

#Region "SetForm"

    Sub CreateControlMP()

        Dim lblForm As Label = CType(Master.FindControl("lblForm"), Label)
        lblForm.Text = "เขต"
    End Sub

#End Region

#Region " Even Button "

    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
            IsDataBind()
            clearGvIndex()
        SaveLogSearch()

    End Sub

    Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        Try
            If chkBeforeSave() Then
                sDeptEntity = New UserEntities
                Dim sZone As New SZONE

                sZone.ZONECODE = txtZoneCode.Text
                sZone.ZONENAME = txtZoneName.Text
                sZone.DEPTCODE = ddlDepartment.SelectedValue


                sDeptEntity.AddToSZONE(sZone)
                sDeptEntity.SaveChanges()

                SaveLogNew()

                IsDataBind()
                reset()

                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resMsgKYC.msgSave + "')", True)

            Else
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + strMsg + "')", True)

            End If
        Catch ex As System.Data.UpdateException

            Dim codeError() As String = ex.InnerException.Message.Split(":")
            If codeError(0) = "ORA-00001" Then
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('ไม่สามารถเพิ่มได้ เนื่องจากรหัสนี้มีการนำมาใช้ในระบบแล้ว')", True)
            Else
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + ex.InnerException.Message + "')", True)
            End If
            WriteError(ex, "btnAdd_Click", "frmZone")
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('บันทึกผิดพลาด')", True)
            WriteError(ex, "btnAdd_Click", "frmZone")
        End Try
    End Sub

    Protected Sub btnModify_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnModify.Click
     


        Try
            If chkBeforeSave() Then
                sDeptEntity = New userEntities
                Dim sDepartment As New SDEPARTMENT

                Dim qry = (From ZONE In sDeptEntity.SZONE Where ZONE.ZONECODE = txtZoneCode.Text).ToList
                'txtPoscode.Text = qry(0).POSCODE
                qry(0).ZONENAME = txtZoneName.Text
                qry(0).DEPTCODE = ddlDepartment.SelectedValue
                sDeptEntity.SaveChanges()

                SaveLogEdit()

                IsDataBind()
                reset()

                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resMsgKYC.msgSave + "')", True)

            Else
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + strMsg + "')", True)
            End If

        Catch ex As System.Data.UpdateException
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + ex.InnerException.Message + "')", True)
            WriteError(ex, "btnModify_Click", "frmZone")
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('บันทึกผิดพลาด')", True)
            WriteError(ex, "btnModify_Click", "frmZone")
        End Try


    End Sub

    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click

        If Not (gvZone.SelectedIndex = -1) Then
            Dim ZoneC As String = gvZone.Rows(gvZone.SelectedIndex).Cells(1).Text
            Try
                sDeptEntity = New userEntities
                Dim qry = (From s_Zone In sDeptEntity.SZONE Where s_Zone.ZONECODE = ZoneC).ToList
                sDeptEntity.DeleteObject(qry(0))
                sDeptEntity.SaveChanges()

                SaveLogDelete(ZoneC)

                IsDataBind()
                reset()

            Catch ex As System.Data.UpdateException
                Dim codeError() As String = ex.InnerException.Message.Split(":")
                If codeError(0) = "ORA-02292" Then
                    ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('ไม่สามารถลบได้ เนื่องจากมีการนำมาใช้ในระบบแล้ว')", True)
                Else
                    ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + ex.InnerException.Message + "')", True)
                End If
                WriteError(ex, "btnDelete_Click", "frmZone")
            Catch ex As Exception
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resError.errorMessage + "')", True)
                WriteError(ex, "btnDelete_Click", "frmZone")
            End Try

        Else
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resValidate.nonSelectGridDelete + "')", True)

        End If

    End Sub

    Protected Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClear.Click
        clear()
    End Sub

    Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        Dim param As String = "{ 'rptType' : '9'," _
                              & "'deptCode' : '" & ddlDepartment.SelectedValue & "/" & ddlDepartment.SelectedItem.Text & "'," _
                              & "'zoneCode' : '" & txtZoneCode.Text.Trim & "'," _
                              & "'zoneName' : '" & txtZoneName.Text.Trim & "'}"
        ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType, "key", "OpenWindowWithPost('../Form/frmPrintRptMaster.aspx','width=730,height=345,left=100,top=100,resizable=yes,scrollbars=yes','Report', " + param + ");", True)
        SaveLogPrint()
    End Sub


#End Region

#Region "Even GridView"

    Protected Sub gvZone_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvZone.SelectedIndexChanged

        If (gvZone.SelectedIndex = intBeforeItemIndex) Then
            clearGvIndex()
            reset()
            btnModify.Text = "แก้ไข"
        Else
            btnModify.Text = "บันทึก"

            Dim txtDeptCode As String = CType(gvZone.Rows(gvZone.SelectedIndex).FindControl("hdfDeptCode"), HiddenField).Value
            setButton(2)

            txtZoneCode.Text = gvZone.Rows(gvZone.SelectedIndex).Cells(1).Text
            txtZoneName.Text = gvZone.Rows(gvZone.SelectedIndex).Cells(2).Text
            If Not (txtDeptCode = "") Then
                ddlDepartment.SelectedValue = txtDeptCode
            Else
                ddlDepartment.SelectedValue = "0"
            End If

            btnDelete.Attributes.Add("onclick", "return confirm('" + String.Format(Resources.resValidate.confirmDelete, _
                       IIf(gvZone.SelectedIndex = -1, "", gvZone.Rows(gvZone.SelectedIndex).Cells(2).Text)) + "');")

        End If
    End Sub
    Protected Sub gvZone_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles gvZone.SelectedIndexChanging
        intBeforeItemIndex = gvZone.SelectedIndex
    End Sub

    Protected Sub gvZone_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gvZone.PageIndexChanging
        Try
            gvZone.PageIndex = e.NewPageIndex
            clearGvIndex()
            DataBind()
        Catch ex As Exception

        End Try
    End Sub

    Protected Sub gvZone_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles gvZone.Sorting
        Dim dt = TryCast(dsZone.Tables("sZone"), DataTable)

        If dt IsNot Nothing Then

            'Sort the data.
            dt.DefaultView.Sort = e.SortExpression & " " & GetSortDirection(e.SortExpression)
            gvZone.DataSource = dsZone.Tables("sZone")
            gvZone.DataBind()
            clearGvIndex()
        End If
    End Sub

#End Region

#Region " Function"

    Private Sub loadDataToDropDown(Optional ByVal strDeptCode As String = "", Optional ByVal strZoneCode As String = "")

        Try
            clsMasterDropDown.setDeptToDdlSearch(ddlDepartment, _
                                       strDeptCode:=clsSessionMenuRight.getDeptCode, _
                                       strRoleCode:=clsSessionMenuRight.getRoleGroup)

        Catch ex As Exception
            Throw ex
            WriteError(ex, "loadDataToDropDown", "frmZone")
        End Try



    End Sub

    Private Sub setUserRightButton()
        Try
            Dim col As New Collection
            col.Add(btnSearch, statusbtn.Query.ToString)
            col.Add(btnAdd, statusbtn.Add.ToString)
            col.Add(btnModify, statusbtn.Modify.ToString)
            col.Add(btnDelete, statusbtn.delete.ToString)
            col.Add(btnPrint, statusbtn.print.ToString)
            setBtnToUserRight(col, strMenuCode, clsSessionMenuRight.getDsMenuRight)
        Catch ex As Exception
            Throw ex
            WriteError(ex, "setUserRightButton", "frmZone")
        End Try
    End Sub

    Private Sub clearGvIndex()
        gvZone.SelectedIndex = -1
        '  btnDelete.Attributes.Clear()
    End Sub

    Private Sub IsDataBind()
        Try

            sDeptEntity = New UserEntities

            If dsZone.Tables.Contains("sZone") Then
                dsZone.Tables.Clear()
            End If

            Dim qryZone = From zone In sDeptEntity.SZONE Group Join dept In sDeptEntity.SDEPARTMENT _
                       On zone.DEPTCODE Equals dept.DEPTCODE Into tblLeftZone = Group
                      From tblZone In tblLeftZone.DefaultIfEmpty
                      Where zone.ZONECODE <> "ZZZ"
                        Order By zone.ZONECODE
                    Select zone.ZONECODE, zone.ZONENAME, tblZone.DEPTCODE, tblZone.DEPTNAME

            If Not (txtZoneCode.Text = "") Then
                qryZone = qryZone.Where(Function(zone) zone.ZONECODE.Contains(txtZoneCode.Text))
            End If

            If Not (txtZoneName.Text = "") Then
                qryZone = qryZone.Where(Function(zone) zone.ZONENAME.Contains(txtZoneName.Text))
            End If

            If Not (ddlDepartment.SelectedValue = "0") Then
                qryZone = qryZone.Where(Function(zone) zone.DEPTCODE = ddlDepartment.SelectedValue)
            End If

            dsZone.Tables.Add(clsDataTable.LINQToDataTable(qryZone, "sZone").Copy)

            If (qryZone.Count = 0) Then
                lblMsg.Visible = True
                lblTotal.Text = ""
            Else
                lblMsg.Visible = False
                lblTotal.Text = "จำนวนรายการทั้งหมด " + qryZone.Count.ToString + " รายการ "

            End If

            gvZone.DataSource = dsZone.Tables("sZone")
            gvZone.DataBind()

            clsDataTable = Nothing
        Catch ex As Exception
            WriteError(ex, "IsDataBind", "frmZone")
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + "เกิดข้อผิดพลาดในการโหลด" + "')", True)

        End Try
    End Sub

    Private Function GetSortDirection(ByVal column As String) As String
        ' By default, set the sort direction to ascending.
        Dim sortDirection = "DESC"
        Try
            ' Retrieve the last column that was sorted.
            Dim sortExpression = TryCast(ViewState("SortExpression"), String)

            If sortExpression IsNot Nothing Then
                ' Check if the same column is being sorted.
                ' Otherwise, the default value can be returned.
                If sortExpression = column Then
                    Dim lastDirection = TryCast(ViewState("SortDirection"), String)
                    If lastDirection IsNot Nothing _
                      AndAlso lastDirection = "DESC" Then

                        sortDirection = "ASC"

                    End If
                End If
            End If

            ' Save new values in ViewState.
            ViewState("SortDirection") = sortDirection
            ViewState("SortExpression") = column
        Catch ex As Exception
            WriteError(ex, "GetSortDirection", "frmZone")
        End Try

        Return sortDirection
    End Function

    Private Sub setButton(ByVal button As Integer)

        If button = 1 Then 'unselect
            lblMsg.Visible = False

            btnModify.Enabled = False
            btnDelete.Enabled = False

            btnSearch.Enabled = True
            btnAdd.Enabled = True

            txtZoneCode.Enabled = True

        ElseIf button = 2 Then 'select

            btnSearch.Enabled = False
            btnAdd.Enabled = False

            btnModify.Enabled = True
            btnDelete.Enabled = True

            txtZoneCode.Enabled = False

        End If

    End Sub

    Private Sub clear()
        If (dsZone.Tables.Contains("sZone")) Then
            dsZone.Tables("sZone").Clear()
            gvZone.DataSource = dsZone.Tables("sZone")
            gvZone.DataBind()
        End If
        clearGvIndex()
        setButton(1)
        lblMsg.Visible = False
        txtZoneCode.Text = ""
        txtZoneName.Text = ""
        lblTotal.Text = ""
        btnModify.Text = "แก้ไข"
    End Sub

    Private Sub reset()
        'gvUserRight.DataSource = dsUserRight.Tables("sUserRight")
        'gvUserRight.DataBind()
        clearGvIndex()
        setButton(1)
        lblMsg.Visible = False
        txtZoneCode.Text = ""
        txtZoneName.Text = ""
        ddlDepartment.SelectedValue = 0
    End Sub

    Private Function chkBeforeSave() As Boolean
        Dim result As Boolean = True


        If (txtZoneCode.Text = "") Then
            result = False
            strMsg = strMsg & "กรุณาระบุรหัสเขต" & "\n"
        End If

        If (txtZoneName.Text = "") Then
            result = False
            strMsg = strMsg & lblZoneName.Text & " : " & "กรุณาระบุชื่อเขต" & "\n"

        End If

        If (ddlDepartment.SelectedValue = "0") Then
            result = False
            strMsg = strMsg & "กรุณาระบุฝ่าย" & "\n"
        End If

        Return result

    End Function

    Private Sub SaveLogSearch()
        Try

            Dim desc As String = ""

            If Not (ddlDepartment.SelectedValue = "0") Then
                desc += " ฝ่าย - " + ddlDepartment.SelectedItem.Text
            End If

            If Not (txtZoneCode.Text = "") Then
                desc += " รหัสเขต - " + txtZoneCode.Text
            End If

            If Not (txtZoneName.Text = "") Then
                desc += " ชื่อเขต - " + txtZoneName.Text
            End If


            If Not desc = "" Then
                desc = "ค้นหาข้อมูลเขต จาก " + desc
            Else
                desc = "ค้นหาทั้งหมด"
            End If

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction("", clsSessionMenuRight.getUserName, 1, desc, "M63")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub SaveLogPrint()
        Try

            Dim desc As String = "พิมพ์ข้อมูลเขต"

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction("", clsSessionMenuRight.getUserName, 2, desc, "M63")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub SaveLogNew()
        Try

            Dim desc As String = "บันทึก ข้อมูลเขต (รหัสเขต " + txtZoneCode.Text + ")"

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction(txtZoneCode.Text, clsSessionMenuRight.getUserName, 3, desc, "M69")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub SaveLogEdit()
        Try

            Dim desc As String = "บันทึก แก้ไข ข้อมูลเขต (รหัสเขต " + txtZoneCode.Text + ")"

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction(txtZoneCode.Text, clsSessionMenuRight.getUserName, 4, desc, "M69")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub SaveLogDelete(ByVal value As String)
        Try

            Dim desc As String = "ลบข้อมูลเขต (รหัสเขต " + value + ")"

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction(value, clsSessionMenuRight.getUserName, 5, desc, "M69")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

#End Region

    

End Class
